package com.om.abom.utils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

import static com.om.abom.config.AbomConfig.*;

@Slf4j
public class ScpClientUtil
{
    private final String ip;

    public ScpClientUtil(String ip)
    {
        this.ip = ip;
    }

    public void getFile(String remoteFile, String localTargetDirectory)
    {
        Connection conn = new Connection(ip, OS_SSH_PORT);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(OS_USERNAME, OS_PASSWORD);
            if (!isAuthenticated) {
                System.err.println("authentication failed");
                return;
            }
            SCPClient client = new SCPClient(conn);
            client.get(remoteFile, localTargetDirectory);
        } catch (IOException ex) {
            log.error("exception message: ", ex);
        } finally {
            conn.close();
        }
    }

    public void putFile(String localFile, String remoteTargetDirectory)
    {
        putFile(localFile, null, remoteTargetDirectory);
    }

    public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory)
    {
        putFile(localFile, remoteFileName, remoteTargetDirectory, null);
    }

    public void putFile(String localFile, String remoteFileName, String remoteTargetDirectory, String mode)
    {
        Connection conn = new Connection(ip, OS_SSH_PORT);
        try {
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(OS_USERNAME, OS_PASSWORD);
            if (!isAuthenticated) {
                System.err.println("authentication failed");
                return;
            }
            SCPClient client = new SCPClient(conn);
            if (mode == null || mode.isEmpty()) {
                mode = "0600";
            }
            if (remoteFileName == null) {
                client.put(localFile, remoteTargetDirectory);
            } else {
                client.put(localFile, remoteFileName, remoteTargetDirectory, mode);
            }
        } catch (IOException ex) {
            log.error("exception message: ", ex);
        } finally {
            conn.close();
        }
    }
}